package com.dsteiner.widgets.client.controller;

import com.dsteiner.widgets.client.IJsUtil;
import com.dsteiner.widgets.client.JsUtil;
import com.dsteiner.widgets.client.Widgets.HTMLExt;
import com.dsteiner.widgets.client.Widgets.IHTML;
import com.dsteiner.widgets.client.Widgets.ITimer;
import com.dsteiner.widgets.client.Widgets.TimerExt;
import com.dsteiner.widgets.client.event.EventListener;
import com.dsteiner.widgets.client.event.EventManager;
import com.dsteiner.widgets.client.event.EventManagerImpl;
import com.dsteiner.widgets.client.event.MessageEvent;
import com.dsteiner.widgets.client.resources.WidgetsResources;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.RootPanel;

public class MessageController {

	private IHTML activityHtml;
	private ITimer fadeOutTimer;
	private IJsUtil jsUtil;

	private static MessageController instance;

	public static MessageController getInstance() {
		if (instance == null)
			instance = new MessageController();
		return instance;
	}
	
	public void registerEventManager(EventManager eventManager) {
		eventManager.registerListener(MessageEvent.class, new EventListener<MessageEvent>() {

			public void onEvent(MessageEvent event) {
				if(event.isAlert())
					JsUtil.getInstance().showAlert(event.getMessage());
				
				activityHtml.setHTML(event.getMessage());
				activityHtml.setVisible((event.isActivity() || event.isInfo()) && event.getMessage() != null);
				
				if(event.isInfo())
					fadeOutTimer.schedule(2000);
			}
		});
	}

	public void registerActivityHtml(IHTML activityHtml) {
		this.activityHtml = activityHtml;
	}

	public void activate() {
		HTMLExt activityHtml = new HTMLExt();
		activityHtml.addStyleName(WidgetsResources.INSTANCE.css().activityHtml());
		activityHtml.setVisible(false);
		RootPanel.get().add(activityHtml);
		registerEventManager(EventManagerImpl.getInstance());
		registerActivityHtml(activityHtml);
		registerFadeOutTimer(new TimerExt());
		registerJsUtil(JsUtil.getInstance());
	}

	private void registerJsUtil(IJsUtil jsUtil) {
		this.jsUtil = jsUtil;
	}

	private void registerFadeOutTimer(ITimer fadeOutTimer) {
		this.fadeOutTimer = fadeOutTimer;
		fadeOutTimer.setCommand(new Command(){
			public void execute() {
				activityHtml.setVisible(false);
			}
		});
	}

}
